<?php
class Cms_Models_Vocabulary extends Ext_Db_Table
{
	protected $_name = 'cms_vocabulary';

	public function getQueryList()
	{
		return $this->select()->order('vocabulary_id DESC');
	}
	
	public function getTree( $vocabulary )
	{
		if( empty( $vocabulary)){
			return array();
		}
		$rowset = $this->getAdapter()->fetchAll( 
			$this->getAdapter()->select( )
			->from(array('vo' => $this->_name ),array())
			->join( 
				array('ta'=>'cms_taxonomy'), 
				'ta.vocabulary_id = vo.vocabulary_id', 
				array('taxonomy_id', 'title') 
			)
			->where('vo.title =? ', $vocabulary )
		);
		
		if( count( $rowset)){
			return $rowset;
		}
		return array();
 	}
 	
 	public function getName( $vid ) 
 	{
 		$row = $this->find( $vid )->current();
		if( count( $row )) {
			return $row->title;
		}
		return NULL;
 	}
 	
	public function getInfo($vid)
	{
		$tax = new Cms_Models_Taxonomy();
		$info['hdr'] = $this->find( $vid )->current();
		$info['taxonomy'] = $tax->getActiveInArray( $vid );

		return $info;
	}

	public function save( $params, $id = NULL )
	{
		if( !empty( $id) ){
			$row = $this->find( $id )->current();
		} else {		
			$row = $this->createRow();
		}
		$row->setFromArray( $params );
		$vid = $row->save();
		$ctype = new Cms_Models_ContentType();
		$vctype = new Cms_Models_VocabularyContentType();
        foreach( $ctype->getAll() as $ctype){
	        if( $params["vocabulary_ctype".$ctype->content_type_id] == 1 ){
	        	$vctype->save( array( 
	        		'vocabulary_id' => $vid, 
	        		'content_type_id' => $ctype->content_type_id 
	        	));
	        }
        }
        return $vid;
	}
}